package io.renren.midplat.fuseclick.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.CharUtils;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.HttpUtils;
import io.renren.midplat.fuseclick.model.OfferCapDTO;
import io.renren.midplat.fuseclick.model.OfferGeoDTO;
import io.renren.midplat.fuseclick.model.ResultDTO;
import io.renren.modules.offer.entity.OfferEntity;
import io.renren.modules.offer.entity.OfferPlatformEntity;
import io.renren.modules.offer.service.OfferService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * batchGetOffersByOfferslook为spring bean的名称
 *
 * @Description /aff/v1/batches/offers
 * @Author haijun.zhang@luckincoffee.com
 * @Date 2018-08-07 9:45
 */
@Component("batchSetOffersByfuseclick")
public class BatchSetOffers {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BatchSetOffers.class);
    @Autowired
    private OfferService offerService;
    @Value("${fuseclick.apiDomain}")
    private String apiDomain;
    @Value("${fuseclick.setOfferURI}")
    private String setOfferURI;
    @Value("${fuseclick.key}")
    private String key;

    private String trackingURL = "&aff_sub1={TID}&source_id={sub_affid}&ios_idfa={device_id}&google_id={s2}";
    @Value("${fuseclick.payoutPCT}")
    private String payoutPCT;

    private String batchNo;


    /**
     * URL 转码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    //@Async
    public void taskRun() {
        LOGGER.info("当前线程:" + Thread.currentThread().getName());
        try {
            batchNo = DateUtils.get14date();
            LOGGER.info("批次号:" + batchNo);

            LOGGER.info("batchSetOffersByfuseclick start");

            Map<String, Object> queryParams = new LinkedHashMap<>();
            queryParams.put("push_flag", 0);
            List<OfferEntity> offerEntityList = offerService.selectByMap(queryParams);

            LOGGER.info("offerEntityList.size():" + offerEntityList.size());
            for (OfferEntity offerEntity : offerEntityList) {
                LOGGER.info("offerEntity:" + offerEntity.toString());
                pushOne(offerEntity);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("batchGetOffersByOfferslook ERROR");
            e.printStackTrace();
        }
        LOGGER.info("batchSetOffersByfuseclick end");
    }

    public void pushOne(OfferEntity offerEntity) {
        try {

            Map<String, String> header = new LinkedHashMap();
            header.put("Content-type", "application/x-www-form-urlencoded");

            Map<String, String> params = new LinkedHashMap();

            //如果数据库中没有下游offerId，则是新增操作。不对ID进行设置 如果有，则是更新操作
            if (offerEntity.getSspOfferId() != null && offerEntity.getSspOfferId() != 0) {
                params.put("id", offerEntity.getSspOfferId() + "");
            }
            params.put("advertiser_id", "26");
            params.put("name", offerEntity.getName());

            //Active/Pending/Paused/Archived
            //TODO params.put("status",offerEntity.getPushStatus());
            if (offerEntity.getPushStatus().equals("Active")) {
                params.put("status", "Active");
            } else if (offerEntity.getPushStatus().equals("Paused")) {
                params.put("status", "Paused");
            }

            params.put("expire_date", DateUtils.toSlashDate(offerEntity.getEndDate()));

            //Desktop/Mobile/Tablet
            params.put("type", "Mobile");
            params.put("conversion_point", "Download and Install");
            params.put("preview_url", CharUtils.toEncodeExistCommon(offerEntity.getPreviewUrl()));

            //TODO 需要可配置
            params.put("url", offerEntity.getTrackingLink() + trackingURL);

            //TODO 需要业主决定 Public/Need Approval/Private
            params.put("access_type", "Need Approval");
            //params.put("access_type",transApproval(offerEntity.getOfferApproval()));

            params.put("ssl", "0");

            //Server Postback URL/iFrame Pixel/Image Pixel
            params.put("tracking_protocol", "Server Postback URL");

            //TODO 需要转换 对比一下LIST
            params.put("currency", "1");

            //TODO 检查一下转换类型 CPA/CPC/CPS/CPI/CPA+CPS/CPL
            params.put("payout_type", offerEntity.getPricingType());

            //TODO 需要可配置payoutPCT
            params.put("payout", Float.parseFloat(offerEntity.getPayout()) * Float.parseFloat(payoutPCT) + "");
            //params.put("payout_percent","");
            params.put("revenue_type", transRevenueType(offerEntity.getPricingType()));
            params.put("revenue", offerEntity.getPayout());
            //params.put("revenue_percent","");
            params.put("need_security_token", "0");
            params.put("force_unique", "0");
            params.put("session_lifespan", "1 Week");
            params.put("hide_referrer", "0");
            //params.put("secondary_offer","");
            params.put("description", offerEntity.getDescription());
            //params.put("restriction","");
            params.put("has_cap_limit", "1");
            //TODO Budget/Conversion 为空的话JSON转换一下
            params.put("cap_type", "Conversion");
            //params.put("cap_event_range","");
            //params.put("cap_overall_limit","");
            params.put("cap_interval", "Daily");
            //TODO 无则默认500  有则用上游的  做成可配置
            if(offerEntity.getOfferCap()!=null){
                OfferCapDTO offerCapDTO = JSON.parseObject(offerEntity.getOfferCap(),OfferCapDTO.class);
                if(offerCapDTO!=null && offerCapDTO.getCap_type()!=null){
                    if(offerCapDTO.getCap_type().equals("2")){
                        params.put("cap_interval_limit", offerCapDTO.getCap_conversion()+"");
                    }
                }
            }
            if(!params.containsKey("cap_interval_limit")){
                params.put("cap_interval_limit", "500");
            }

            //params.put("cap_affiliate_overall_limit","");
            //params.put("cap_affiliate_interval","");
            //params.put("cap_affiliate_interval_limit","");
            params.put("device_targeting", "1");

            //设置deviceRules 有特殊转换规则
            if (offerEntity.getOfferPlatform() != null) {
                drviceRules(offerEntity.getOfferPlatform(), params);
            }
            //params.put("device_redirect_offer_id","");
            params.put("geo_targeting", "1");
            params.put("geo_type", "1");

            //设置geo_countries 有特殊转换规则
            if (offerEntity.getOfferGeo() != null) {
                countryRules(offerEntity.getOfferGeo(), params);
            }

            params.put("geo_enforce", "1");
            //params.put("geo_redirect_type","");
            //params.put("geo_redirect_target_id","");
            params.put("app_id", getAppId(offerEntity.getPreviewUrl()));
            //params.put("categories","");

            String response = HttpUtils.doPost(apiDomain + setOfferURI + key, params, header);
            LOGGER.info("response:" + response);
            if (response != null) {
                ResultDTO resultDTO = JSON.parseObject(response, ResultDTO.class);
                if (resultDTO.getHttpStatus() == 201) {
                    offerEntity.setSspOfferId(resultDTO.getData().get(0).getId());
                    offerEntity.setPushFlag(1);
                    offerEntity.setBak("上传新建数据成功");
                    LOGGER.info("上传下游数据Create:{},Name:{}", offerEntity.getId(), offerEntity.getName());
                } else if (resultDTO.getHttpStatus() == 202) {
                    offerEntity.setPushFlag(1);
                    offerEntity.setBak("更新数据成功");
                    LOGGER.info("上传下游数据Update:{},Name:{}", offerEntity.getId(), offerEntity.getName());
                } else {
                    LOGGER.error("上传下游数据异常: id:{},HttpStatus():{},ErrorMessage:{}", offerEntity.getId(), resultDTO.getHttpStatus(), resultDTO.getMessage());
                    offerEntity.setPushFlag(2);
                    offerEntity.setBak("上传下游数据异常: ErrorCode:" + resultDTO.getHttpStatus() + "ErrorMessage:" + resultDTO.getMessage());
                }

                offerService.updateById(offerEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //CPA · CPC · CPS · CPA+CPS
    public String transRevenueType(String revenueType) {
        if (revenueType.equals("CPA")) {
            return "RPA";
        } else if (revenueType.equals("CPC")) {
            return "RPC";
        } else if (revenueType.equals("CPS")) {
            return "RPS";
        } else if (revenueType.equals("CPA+CPS")) {
            return "RPA+RPS";
        }
        return "";
    }

    public static String getAppId(String appId) {
        if (appId.startsWith("https://play.google.com")) {
            String a = appId.substring(appId.lastIndexOf("id=") + 3);
            System.out.println(a.indexOf('&'));
            if(a.indexOf('&')>-1){
                a = a.substring(0,a.indexOf('&'));
            }
            return a;
        }
        if (appId.startsWith("https://itunes.apple.com")) {
            String a = appId.substring(appId.lastIndexOf("/id") + 1);
            System.out.println(a.indexOf('?'));
            if(a.indexOf('?')>-1){
                a = a.substring(0,a.indexOf('?'));
            }
            return a;
        }
        return "";
    }

    public static void main(String [] args){
        String a = "https://play.google.com/store/apps/details?id=com.egg.foodandroid&hl=en&gl=TH";
        System.out.println(getAppId(a));
    }

    /**
     * 1 Require Approval 需要批准
     * 2 Public 公共
     * 3 Private 个人
     */
    public String transApproval(int offerApproval) {

        if (offerApproval == 1) {
            return "Need Approval";
        } else if (offerApproval == 2) {
            return "Public";
        } else if (offerApproval == 3) {
            return "Private";
        }
        return "";
    }


    public static void drviceRules(String json, Map<String, String> params) {
        JSONObject jsonObject = JSON.parseObject(json);
        JSONArray targetArray = jsonObject.getJSONArray("target");

        int i = 0;
        for (Object obj : targetArray) {
            JSONObject jsonObject2 = (JSONObject) obj;
            OfferPlatformEntity offerPlatformEntity = JSONObject.parseObject(jsonObject2.toJSONString(), OfferPlatformEntity.class);
            String drviceRules = "";
            if (offerPlatformEntity.getIsAbove() == 0) {
                drviceRules = offerPlatformEntity.getSystem() + "";
            } else {
                drviceRules = offerPlatformEntity.getSystem() + "(" + offerPlatformEntity.getAboveVersion() + "-)";
            }
            params.put("device_rules[" + i + "]", "1:OS:" + drviceRules);
            ++i;
        }
    }

    public static void countryRules(String json, Map<String, String> params) {
        OfferGeoDTO offerGeoDTO = JSON.parseObject(json, OfferGeoDTO.class);
        List<OfferGeoDTO.TargetBean> targetList = offerGeoDTO.getTarget();
        int i = 0;
        for (OfferGeoDTO.TargetBean targetBean : targetList) {
            if ("UK".equals(targetBean.getCountry_code())) {
                params.put("geo_countries[" + i + "]", "GB");
            } else {
                params.put("geo_countries[" + i + "]", targetBean.getCountry_code());
            }

            ++i;
        }
    }
}